package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.Complain;
import cn.edu.tju.elm.repository.ComplainRepository;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * ClassName: ComplainService
 * Package: cn.edu.tju.elm.service
 * Description: 投诉服务层
 *
 * @Author System
 * @Create 2025/10/31
 * @Version 1.0
 */
@Service
@Transactional
public class ComplainService {

    private final ComplainRepository complainRepository;

    public ComplainService(ComplainRepository complainRepository) {
        this.complainRepository = complainRepository;
    }

    /**
     * 添加投诉
     */
    public Complain addComplain(Complain complain) {
        // 检查该订单是否已存在投诉
        if (complainRepository.existsByOrderIdAndDeletedFalse(complain.getOrder().getId())) {
            throw new IllegalArgumentException("该订单已存在投诉，一个订单只能提交一次投诉。");
        }
        complain.setState(0); // 初始状态为待审核
        return complainRepository.save(complain);
    }

    /**
     * 根据ID查询投诉
     */
    public Optional<Complain> getComplainById(Long id) {
        return complainRepository.findById(id)
                .filter(c -> !c.getDeleted());
    }

    /**
     * 根据用户ID查询投诉列表
     */
    public List<Complain> getComplainsByCustomerId(Long customerId) {
        return complainRepository.findByCustomerIdAndDeletedFalse(customerId);
    }

    /**
     * 根据商家ID查询投诉列表
     */
    public List<Complain> getComplainsByBusinessId(Long businessId) {
        return complainRepository.findByBusinessIdAndDeletedFalse(businessId);
    }

    /**
     * 根据订单ID查询投诉
     */
    public Optional<Complain> getComplainByOrderId(Long orderId) {
        return complainRepository.findByOrderIdAndDeletedFalse(orderId);
    }

    /**
     * 根据状态查询投诉列表
     */
    public List<Complain> getComplainsByState(Integer state) {
        return complainRepository.findByStateAndDeletedFalse(state);
    }

    /**
     * 查询所有投诉
     */
    public List<Complain> getAllComplains() {
        return complainRepository.findByDeletedFalse();
    }

    /**
     * 更新投诉
     */
    public Complain updateComplain(Complain complain) {
        complain.setUpdateTime(LocalDateTime.now());
        return complainRepository.save(complain);
    }

    /**
     * 商家处理投诉（同意或拒绝）
     */
    public Complain businessHandleComplain(Long complainId, Integer newState, String reply) {
        Complain complain = getComplainById(complainId)
                .orElseThrow(() -> new EntityNotFoundException("投诉不存在，ID: " + complainId));

        // 检查状态
        if (complain.getState() == 2) {
            throw new IllegalStateException("该投诉已通过，无法更改");
        }

        // 只能设置为拒绝(1)或通过(2)
        if (newState != 1 && newState != 2) {
            throw new IllegalArgumentException("商家只能设置投诉状态为拒绝(1)或通过(2)");
        }

        complain.setState(newState);
        complain.setBusinessReply(reply);
        complain.setUpdateTime(LocalDateTime.now());
        return complainRepository.save(complain);
    }

    /**
     * 管理员处理投诉（同意或拒绝）
     */
    public Complain adminHandleComplain(Long complainId, Integer newState, String reply) {
        Complain complain = getComplainById(complainId)
                .orElseThrow(() -> new EntityNotFoundException("投诉不存在，ID: " + complainId));

        // 检查状态
        if (complain.getState() == 2) {
            throw new IllegalStateException("该投诉已通过，无法更改");
        }

        // 可以设置为通过(2)或管理员拒绝(3)
        if (newState != 2 && newState != 3) {
            throw new IllegalArgumentException("管理员只能设置投诉状态为通过(2)或拒绝(3)");
        }

        complain.setState(newState);
        complain.setAdminReply(reply);
        complain.setUpdateTime(LocalDateTime.now());
        return complainRepository.save(complain);
    }

    /**
     * 软删除投诉
     */
    public void deleteComplain(Long id) {
        Complain complain = getComplainById(id)
                .orElseThrow(() -> new EntityNotFoundException("投诉不存在，ID: " + id));

        complain.setDeleted(true);
        complain.setUpdateTime(LocalDateTime.now());
        complainRepository.save(complain);
    }

    /**
     * 统计用户的投诉数量
     */
    public Long countByCustomerId(Long customerId) {
        return complainRepository.countByCustomerId(customerId);
    }

    /**
     * 统计商家的投诉数量
     */
    public Long countByBusinessId(Long businessId) {
        return complainRepository.countByBusinessId(businessId);
    }

    /**
     * 统计商家待处理的投诉数量
     */
    public Long countPendingByBusinessId(Long businessId) {
        return complainRepository.countPendingByBusinessId(businessId);
    }
}

